package novemberBot.sensor;

import lejos.nxt.LightSensor;
import lejos.nxt.SensorPort;

/**Checks its light sensor and updates a boolean depending on its current state
 * ie on a line or not
 * @author Antoine Lennartz*/
public class LeftLineChecker extends Thread implements LineChecker{
	/**attached Light Sensor set by Constructor*/
	private LightSensor ls;
	
	/**light level for line*/
	public static int THRESHOLD=500;
	
	/**state boolean*/
	private boolean onLine=false;
	/**lock for synchronizing the onLine boolean*/
	private Object stateLock=new Object();
	/**whether or not the checker is enabled*/
	private boolean enable=false;
	/**whether or not the line checker */
	private boolean corrected = false;
	
	
	/**Constructor*/
	public LeftLineChecker(SensorPort s){
		ls = new LightSensor(s);
		this.start();
		ls.setFloodlight(true);
		//Debugger.pauseLCDI();
		try{Thread.sleep(40);}catch(Exception e){}
		THRESHOLD=ls.getNormalizedLightValue()-30;
		//Debugger.breakPoint(""+THRESHOLD);
	}
	
	public void run(){
		while(true){
			if(enable){
				//Debugger.pauseLCDI();
				//System.out.println(ls.getNormalizedLightValue());
				setOnLine(isOnLine());
				try { Thread.sleep(30);
				} catch (InterruptedException e) {
				}
			}else Thread.yield();
		}
	}
	/**checks to see if the sensor is on a line or not*/
	private boolean isOnLine(){
		//Debugger.audibleDebug(200, 100);
		int value=ls.readNormalizedValue();
		if(value-THRESHOLD>60 && !corrected){
			THRESHOLD+=60;
			corrected = true;
		}
		//Debugger.pauseLCDI();
		//System.out.println(value-THRESHOLD);
		return value<THRESHOLD;
	}
	
	@Override
	public void setEnable(boolean enable){
		this.enable=enable;
	}
	
	/**synchronized mutator for state boolean*/
	private void setOnLine(boolean onLine){
		synchronized(stateLock){
			this.onLine=onLine;
		}
	}
	
	/**synchronized accessor for state boolean*/
	@Override
	public boolean onLine(){
		synchronized(stateLock){
			return onLine;
		}
	}


	
}
